package com.wonder.admin.config;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.MappedInterceptor;

import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.context.support.ConversionServiceFactoryBean;

import com.wonder.common.config.WonderConfig;
import com.wonder.common.constants.Constants;
import com.wonder.config.GlobalFormDateConvert;
import com.wonder.config.GlobalJsonDateConvert;
import com.wonder.admin.interceptor.AdminTokenInterceptor;


/**
 * 通用配置
 * 
 * @author
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

	@Value("${swagger.basic.username}")
	private String username;
	@Value("${swagger.basic.password}")
	private String password;
	@Value("${swagger.basic.check}")
	private Boolean check;

//    @Autowired
//    private RepeatSubmitInterceptor repeatSubmitInterceptor;

	@Bean
	public HandlerInterceptor adminTokenInterceptor() {
		return new AdminTokenInterceptor();
	}
	


	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		/** 本地文件上传路径 */
		registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
				.addResourceLocations("file:" + WonderConfig.getProfile() + "/");

		/** swagger配置 */
		registry.addResourceHandler("/swagger-ui/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
				.resourceChain(false);

		// registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		// registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}

	/**
	 * 自定义拦截规则
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");

		// 后台token拦截
		registry.addInterceptor(adminTokenInterceptor()).addPathPatterns("/admin/**").addPathPatterns("/app/**")
				.excludePathPatterns("/admin/Login/**").excludePathPatterns("/admin/login/**")
				.excludePathPatterns("/admin/logout")
				.excludePathPatterns("/admin/AdminUser/**")
				.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui/**")
				.excludePathPatterns("/wallet/RedPacket/**");
	
	}

//    /**
//     * 跨域配置
//     */
//    @Bean
//    public CorsFilter corsFilter()
//    {
//        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration config = new CorsConfiguration();
//        config.setAllowCredentials(true);
//        // 设置访问源地址
//        config.setAllowedOriginPatterns("*");
//        // 设置访问源请求头
//        config.addAllowedHeader("*");
//        // 设置访问源请求方法
//        config.addAllowedMethod("*");
//        // 对接口配置跨域设置
//        source.registerCorsConfiguration("/**", config);
//        return new CorsFilter(source);
//    }
	
  /**
  * 跨域配置
  */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowedOriginPatterns("*").allowCredentials(true)
				.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH").maxAge(3600);
	}
	
	
	//JSON格式 全局日期转换器配置
    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //设置日期格式
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(GlobalJsonDateConvert.instance);
        //防止前台传送的属性在BEAN中没有时报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        //设置中文编码格式
        List<MediaType> list = new ArrayList<MediaType>();
        //list.add(MediaType.APPLICATION_JSON_UTF8);
        list.add(new MediaType("application", "json"));
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
        return mappingJackson2HttpMessageConverter;
    }

    //表单格式 全局日期转换器

    @Bean
    @Autowired
    public ConversionService getConversionService(GlobalFormDateConvert globalDateConvert){
        ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();
        Set<Converter> converters = new HashSet<>();
        converters.add(globalDateConvert);
        factoryBean.setConverters(converters);
        return factoryBean.getObject();
    }




	/* 必须在此处配置拦截器,要不然拦不到swagger的静态资源 */
//    @Bean
//    @ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
//    public MappedInterceptor getMappedInterceptor() {
//        return new MappedInterceptor(new String[]{"/swagger-ui.html", "/webjars/**"}, new SwaggerInterceptor(username, password, check));
//    }
}
